import React, { Component } from 'react'
import './index.less';
import { NavBar, List, Button, Toast} from 'antd-mobile'
import axios from 'axios';

export default class UserCenter extends Component {
    state = {
        //如果数据是多条数据, 选择数组保存, 如果只有一条数据, 使用对象保存
        user: {}
    }

    render() {
        let {avatar, username, nickName,phone} = this.state.user;
        return (
            <div className="user-container">
                {/* 顶部 */}
                <NavBar back={null} style={{background: 'white'}}>个人中心</NavBar>

                {/* 头像与用户名 */}
                <div className="profile">
                    <div>
                        <img src={avatar} alt="" />
                    </div>
                    <p className="welcome">欢迎, 用户 {username}</p>
                </div>  

                {/* 个人信息 */}
                <div className="info">
                    <List>
                        <List.Item>
                            <span>
                                昵称
                            </span>
                            <span>
                                {nickName}
                            </span>
                        </List.Item>
                        <List.Item>
                            <span>
                                手机号
                            </span>
                            <span>{phone}</span>
                        </List.Item>
                    </List>
                </div>

                <div className="gap-10"></div>
                <div className="gap-10"></div>
                <div className="gap-10"></div>
                <div className="gap-10"></div>
                <div className="gap-10"></div>
                {/* 按钮 */}
                <Button block color="danger" onClick={this.logout}>退出登录</Button>
            </div>
        )
    }

    async componentDidMount(){
        let result = await axios.post('/login/verify');
        this.setState({
            user: result.data.data
        })
    }

    //退出登录
    logout = async () => {
        //获取 id
        let {_id} = this.state.user;
        //发送请求
        let result = await axios.post('/logout');
        //检查结果
        console.log(result.data);
        //退出成功的情况
        if(result.data.code === 20000){
            Toast.show({
                icon: 'success',
                content: '成功退出',
                afterClose: () => {
                    this.props.history.push('/login')
                }
            })
        }else{
            Toast.show({
                icon: 'fail',
                content: '退出失败, 稍后再试'
            })
        }
    }
}
